<template>
  <el-dialog
    v-model="visible"
    title="通知级别设置"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="通知级别" prop="level">
        <el-select v-model="form.level" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submitForm"
        >确认</el-button
      >
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { updateAdminTelegramNotificationLevel } from "@/api/adminTelegramApi";
import { message } from "@/utils/message";

interface UserForm {
  level: string;
}
const userId = ref(0);
const options = [
  {
    value: "ALL",
    label: "接收所有通知"
  },
  {
    value: "BUSINESS_ONLY",
    label: "仅接收业务通知"
  },
  {
    value: "NONE",
    label: "不接收通知"
  }
];

const visible = ref(false);

const form = reactive<UserForm>({
  level: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  level: [{ required: true, message: "请选择通知级别", trigger: "change" }]
};

const userFormRef = ref<FormInstance>();
const submitLoading = ref(false);

const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        await updateAdminTelegramNotificationLevel(userId.value, form);
        message("设置成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};

const open = (id: number, status: string) => {
  userId.value = id;
  form.level = status;
  visible.value = true;
};

defineExpose({ open });
</script>
